package club.hicode.daydayup.netty.udp.server;

import club.hicode.daydayup.netty.udp.MessageBo;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * @author leizhenyang
 */
public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        String body = packet.content().toString(CharsetUtil.UTF_8);
        body = StrUtil.removeSuffix(body, "$");
        System.out.println(body);

        MessageBo messageBo = JSONUtil.toBean(body, MessageBo.class);
        messageBo.setResult("服务端已收到消息:" + DateUtil.now());
        ThreadUtil.sleep(3, TimeUnit.SECONDS);

        //往客户端发送消息
        String sendStr = JSONUtil.toJsonStr(messageBo) + "$";
        System.out.println("服务端回执消息：" + sendStr);
        DatagramPacket sendPacket = new DatagramPacket(Unpooled.copiedBuffer(sendStr.getBytes()), packet.sender());
        ctx.channel().writeAndFlush(sendPacket);
    }
}
